package com.cat.common.service;
import com.cat.common.entity.Page;
import com.cat.tiger.util.GenericsUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/5/27.
 */
public class PageServiceImpl<T> implements PageService<T>{

    @Autowired
    JdbcTemplate jdbcTemplate;


    public Class<T> getParameterizedType(){
//        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
//        Class<T>  entityClass = (Class<T>) type.getActualTypeArguments()[0];
//        System.out.println("Dao实现类是：" + entityClass.getName());
        return GenericsUtils.getSuperClassGenricType(getClass());
    }


    /**
     * 支持一个主表   参数类型必须和数据库字段一致
     * @param page
     * @param sql
     * @param searchinfo
     * @return
     */

    @Override
    public Page getpageBySingeleTable(Page page, String sql, Map searchinfo) {
        return getPageByDateSourceSingeleTable(page, sql, searchinfo, jdbcTemplate);
    }

    /**
     * 支持一个主表   参数类型必须和数据库字段一致
     * @param page
     * @param sql
     * @param searchinfo
     * @param myjdbcTemplate 要查询的数据源
     * @return
     */

    @Override
    public Page getPageByDateSourceSingeleTable(Page page, String sql, Map searchinfo,JdbcTemplate myjdbcTemplate) {
        StringBuffer wheresql = new StringBuffer();
        StringBuffer countSql = new StringBuffer();
        StringBuffer querysql = new StringBuffer();
        StringBuffer groupsql = new StringBuffer();
        StringBuffer ordersql = new StringBuffer();
        for(Object key :searchinfo.keySet()){
            Object value = searchinfo.get(key);
            if(value instanceof  Integer){
                if(!Integer.valueOf(value+"").equals(-1))
                    wheresql.append(" and t.").append(key).append("=").append(value);
            }else if(value instanceof Long){
                if(!Long.valueOf(value+"").equals(-1L))
                    wheresql.append(" and t.").append(key).append("=").append(value);
            }else if(value instanceof Float){
                if(!Float.valueOf(value+"").equals(-1F))
                    wheresql.append(" and t.").append(key).append("=").append(value);
            }else if(value instanceof  String){
                if(StringUtils.isNotEmpty(value.toString())){
                    //处理时间
                    if("starttime".equals(key)){
                        wheresql.append(" and t.create_time >= '" + value + "'");
                    }else if("endtime".equals(key)){
                        wheresql.append(" and t.create_time <= '"+value+"'");
                    }else{
                        wheresql.append(" and t.").append(key).append("=").append("'"+value+"'");
                    }
                }
            }else{

            }
        }

        if(StringUtils.isNotBlank(page.getGroupBy())){
            groupsql.append(" group by ").append(page.getGroupBy()).append(" ");
        }

        if(StringUtils.isNotBlank(page.getOrderBy())){
            ordersql.append(" order by ").append(page.getOrderBy()).append(" ");
            if(StringUtils.isNotEmpty(page.getOrder()))
                ordersql.append(page.getOrder());
        }


        countSql.append("select count(1) acount from (")
                .append(sql)
                .append(wheresql)
                .append(groupsql)
                .append(") b");

        querysql.append(sql).append(wheresql).append(groupsql).append(ordersql).append(" limit ?,?");
        int count = Integer.valueOf(myjdbcTemplate.queryForList(countSql.toString()).get(0).get("acount")+"");
        List<T> tList = myjdbcTemplate.query(querysql.toString(), new BeanPropertyRowMapper<T>(getParameterizedType()),page.getStart(),page.getPageSize());
        page.setTotalItems(count);
        page.setResult(tList);
        return page;
    }

    public Page<T> findPage(Page<T> page, String sql, Object... params) {
        String countSql = "select count(1) as c from (" + sql + ") t";
        int count = jdbcTemplate.queryForObject(countSql, params, Integer.class);
        page.setTotalItems(count);
        if (count==0) {
            return page;
        }

        String pageSql = sql + " limit " + page.getStart() + "," + page.getPageSize();
        List<T> result = jdbcTemplate.query(pageSql, new BeanPropertyRowMapper<T>(getParameterizedType()), params);
        page.setResult(result);
        return page;
    }

    public Page<T> findPageOnGroupOrder(Page<T> page, String sql, Object... params) {

        StringBuffer countSql = new StringBuffer();
        StringBuffer querysql = new StringBuffer();
        StringBuffer groupsql = new StringBuffer();
        StringBuffer ordersql = new StringBuffer();

        if(StringUtils.isNotBlank(page.getGroupBy())){
            groupsql.append(" group by ").append(page.getGroupBy()).append(" ");
        }

        if(StringUtils.isNotBlank(page.getOrderBy())){
            ordersql.append(" order by ").append(page.getOrderBy()).append(" ");
            if(StringUtils.isNotEmpty(page.getOrder()))
                ordersql.append(page.getOrder());
        }

        countSql.append("select count(1) c from (")
                .append(sql)
                .append(groupsql)
                .append(") t");
        int count = jdbcTemplate.queryForObject(countSql.toString(), params, Integer.class);
        page.setTotalItems(count);
        if (count==0) {
            return page;
        }

        querysql.append(sql).append(groupsql).append(ordersql).append(" limit ").append(page.getStart()).append(",").append(page.getPageSize());
        List<T> result = jdbcTemplate.query(querysql.toString(), new BeanPropertyRowMapper<T>(getParameterizedType()), params);
        page.setResult(result);
        return page;
    }

}
